package LeetCode_Section;/*
 *
 *@author:    Xavier
 *@data:      2023 - 08 - 18
 *@time:      16:35
 *
 */

//用队列实现栈
//https://leetcode.cn/problems/implement-stack-using-queues/



import java.util.LinkedList;
import java.util.Queue;

public class UseQueueRealizeStack {
    private Queue<Integer> qu1;
    private Queue<Integer> qu2;


    public void MyStack() {
        qu1 = new LinkedList<>();
        qu2 = new LinkedList<>();

    }

    public void push(int x) {
        //放到不为空的队列
        if (!qu1.isEmpty()) {
            qu1.offer(x);
        }else if (!qu2.isEmpty()) {
            qu2.offer(x);
        }else {
            qu1.offer(x);
        }
    }

    public int pop() {
        if (empty()) {
            return -1;
        }
        if (!qu1.isEmpty()) {
            int currentSize = qu1.size();
            for (int i = 0; i < currentSize - 1; i++) {
                int x = qu1.poll();
                qu2.offer(x);
            }
            return qu1.poll();//最后一个数据返回
        }
        if (!qu2.isEmpty()) {
            int currentSize = qu2.size();
            for (int i = 0; i < currentSize - 1; i++) {
                int x = qu2.poll();
                qu2.offer(x);
            }
            return qu2.poll();//最后一个数据返回
        }
        return -1;
    }

    public int top() {
        if (empty()) {
            return -1;
        }
        if (!qu1.isEmpty()) {
            int currentSize = qu1.size();
            int x = -1;
            for (int i = 0; i < currentSize; i++) {
                x = qu1.poll();
                qu2.offer(x);
            }
            return x;//最后一个数据返回
        }
        if (!qu2.isEmpty()) {
            int currentSize = qu2.size();
            int x = -1;
            for (int i = 0; i < currentSize; i++) {
                x = qu2.poll();
                qu2.offer(x);
            }
            return x;//最后一个数据返回
        }
        return -1;

    }

    public boolean empty() {
        return qu1.isEmpty() && qu2.isEmpty();

    }

}
